import java.util.*;
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class sum {
  public int sumNumbers(TreeNode root) {
    // Start typing your Java solution below
    // DO NOT write main() function
      if (root == null) {
            return 0;
        } else {
            return sum(root, 0);
        }
    }
    
    public int sum(TreeNode root, int prev) {
        if (root.left == null && root.right == null) {
            return 10 * prev + root.val;
        } else if (root.left != null && root.right != null) {
            return sum(root.left, 10 * prev + root.val) + sum(root.right, 10 * prev + root.val);
        } else if (root.left != null) {
            return sum(root.left, 10 * prev + root.val);
        } else {
            return sum(root.right, 10 * prev + root.val);
        }
    }
}